package com.atguigu.tx.dao.impl;

import com.atguigu.tx.dao.BookDao;
import com.atguigu.tx.exception.BookStockException;
import com.atguigu.tx.exception.UserBalanceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * Date:2020/9/25
 * Author:ybc
 * Description:
 */
@Repository
public class BookDaoImpl implements BookDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Integer getPriceByBookId(Integer bookId) {
        String sql = "select price from t_book where id = ?";
        return jdbcTemplate.queryForObject(sql, Integer.class, bookId);
    }

    @Override
    public void updateBookStock(Integer bookId) {
        //先查询图书的库存
        String sql1 = "select stock from t_book_stock where id = ?";
        Integer stock = jdbcTemplate.queryForObject(sql1, Integer.class, bookId);
        if(stock <= 0){
            throw new BookStockException("库存不足");
        }
        String sql2 = "update t_book_stock set stock = stock - 1 where id = ?";
        jdbcTemplate.update(sql2, bookId);
    }

    @Override
    public void updateUserBalance(Integer userId, Integer price) {
        String sql1 = "select balance from t_user where id = ?";
        Integer balance = jdbcTemplate.queryForObject(sql1, Integer.class, userId);
        if(price > balance){
            throw new UserBalanceException("余额不足");
        }
        String sql2 = "update t_user set balance = balance - ? where id = ?";
        jdbcTemplate.update(sql2, price, userId);
    }
}
